package service.impl;

import entity.ExpireKey;
import entity.ExpireKeyMinHeap;
import service.ExecService;

//过期键管理服务
public class ExpireKeyManageServiceImpl extends Thread{
    private ExecService execService=new ExecServiceImpl();
    private static ExpireKeyMinHeap expireKeyMinHeap;
    public ExpireKeyManageServiceImpl(){
        expireKeyMinHeap=new ExpireKeyMinHeap();
    }

    public static ExpireKeyMinHeap getExpireKeyMinHeap() {
        return expireKeyMinHeap;
    }


    @Override
    public void run() {
        while (true){
            int size=expireKeyMinHeap.size();
            System.out.println("当前过期键长度"+size);
            int count=0;
            while (count++<expireKeyMinHeap.size()){
                ExpireKey head = expireKeyMinHeap.getHead();
                long currentTimeMillis = System.currentTimeMillis();
                Long timeStamp = head.getTimeStamp();
                if (timeStamp>currentTimeMillis) break;
                del(head);
            }
            try {
                //忙等的方式不推荐 是否可以手写一个ScheduledExecutorService?
                if (count>=100)Thread.sleep(2000);
                else Thread.sleep(4000);
            }catch (InterruptedException e){
                throw new RuntimeException();
            }
        }
    }
    public static void add(ExpireKey element){
        expireKeyMinHeap.add(element);
    }

    private static void del(ExpireKey head){
        System.out.println("过期清除"+head);
        expireKeyMinHeap.removeHead();
        ExecService.META_DATA.del(head.getKey());
    }

}
